﻿using FRRJIf;
using RJi.FanucInterface3.Common.Internal;
using RJi.FanucInterface3.Models;

namespace RJi.FanucInterface3.DataParser.Internal;

internal class DataStringParser : IDataParser
{
    public bool CanHandle(VariableMetadata metadata)
    {
        return metadata.DataType == typeof(DataString);
    }

    public object? Parse(VariableMetadata metadata)
    {
        switch (metadata.Ext)
        {
            case "STRING_REG":
            {
                var stringReg = (DataString)metadata.VariableRef;
                var strings = new RbtRegVar[metadata.Count];

                for (var i = 0; i < metadata.Count; i++)
                {
                    string value = null!;
                    var index = i + metadata.StartIndex;
                    if (!stringReg.GetValue(index, ref value)) continue;
                    strings[i] = new RbtRegVar(index, value);
                }

                if (strings.Length == 0) return null;
                return strings.Length == 1 ? strings[0] : strings;
            }
            case "REG_COMMENT":
            {
                var regComment = (DataString)metadata.VariableRef;
                var comments = new RbtRegComment[metadata.Count];

                for (var i = 0; i < metadata.Count; i++)
                {
                    string comment = null!;
                    var index = i + metadata.StartIndex;
                    if (!regComment.GetValue(index, ref comment)) continue;
                    comments[i] = new RbtRegComment(index, comment);
                }

                if (comments.Length == 0) return null;
                return comments.Length == 1 ? comments[0] : comments;
            }
            default:
                return null;
        }
    }
}